<template>
    <div id="add-edit-orgMan">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="769px" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="auto" :rules="rules">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('lk9lluH5w4NRQg1Bt40')" prop="name">
                            <el-input v-model="ruleForm.name" :placeholder="$t('xJ2lys50dooEzgq8a9V')" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('oxaY6Iq4ENkeR9fv9r3Tl')" prop="code">
                            <el-input v-model="ruleForm.code" :placeholder="$t('lGiXTn1829PiF0yrT8E8')" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('vqZ5Nvg6wKn4CYgYgek7q')" prop="pName">
                            <el-select :disabled="isDisabled" value-key="id" @change="organizaChange($event)" v-model="ruleForm.pName" :placeholder="$t('fOkRa7gUevOn8lhuMZnUz')">
                                <el-option
                                    v-for="item in organizaOption"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('fBzbMi6UmAdXw0dU4FkW')" prop="sort">
                            <el-input v-model="ruleForm.sort" :placeholder="$t('z1O2gGdCnPppBkKhYfnMy')" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item :label="$t('jJqL1X8ChQgp81e0Gpzm')" prop="remark">
                            <el-input v-model="ruleForm.remark" :placeholder="$t('98wJzI3lyj0Hk53nqIMpg')" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">{{ $t('gJikJmcygxvlVId7NvzSu') }}</el-button>
                <el-button type="primary" :disabled="repeatDis" @click="submitForm(ruleFormRef)">{{ $t('hfPwhz0wXrlEiXoAqXs9W') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { nextTick , defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue'
import { getOrgList , sysOrgAdd , sysOrgEdit } from '/@/api/manage/manage'
import { FormInstance, FormRules , ElMessage, ElButton, ElCol, ElDatePicker, ElDialog, ElDivider, ElForm, ElFormItem, ElInput, ElOption, ElRadio, ElRow, ElSelect, ElTable, ElTableColumn } from 'element-plus'
import getTableData from '/@/utils/getTableData'
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';
const { proxy } = useCurrentInstance();
const $t = proxy.$t;
import { log } from 'console'
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** ruleFormType 表单数据类型 */
type ruleFormType = {
    id: String | Number,
    name: String,
    code: String | Number,
    pid: String | Number,
    pName: String,
    sort: Number,
    remark: String,
}
export default defineComponent( {
    name: 'add-edit-orgMan',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref()
        const ruleFormRef = ref()
        const organizaOption = ref()
        let setArr: any[] = []
        const isDisabled = ref()

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            name: [
				{ required: true, message: $t('3Wh4xgBqtPn1XzIjgPf'), trigger: 'blur' },
			],
            code: [
				{ required: true, message: $t('hlOzGcF2w1KyZlQ0jvFR'), trigger: 'blur' },
			],
            pName: [
				{ required: true, message: $t('oKz8Y29j08LDgh5s7X8Un'), trigger: 'blur' },
			],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            ctx.emit('cancelUseClick')
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelUseClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    const setObj = toRaw(state.ruleForm)
                    if(setObj.id === ''){
                        const {pName , id , ...param} = setObj
                        let res:any = await sysOrgAdd(param)
                        if(res.success){
                            state.repeatDis = true
                            ctx.emit('controlUseClick','success')
                            ctx.emit('updateData')
                        }else{
                            ctx.emit('controlUseClick','')
                        }
                    }else{
                        const {pName , ...param} = setObj
                        console.log(param,'param')
                        let res:any = await sysOrgEdit(param)
                        if(res.success){
                            state.repeatDis = true
                            ctx.emit('controlUseClick','success')
                            ctx.emit('updateData')
                        }else{
                            ctx.emit('controlUseClick','')
                        }
                        console.log(res,'编辑返回')
                    }
                    return
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /*** organizaChange 部门下拉框改变事件 */
        const organizaChange = (val:any) => {
            state.ruleForm.pid = val.id
            state.ruleForm.pName = val.name
        }

        /*** GetInfo 获取全部部门数据 */
        const GetInfo = async () => {
            try {
                let res: { data: any[] } = await getOrgList()
                organizaOption.value = res.data
                setArr = res.data
                console.log(setArr,'setArr123')
            } catch (err) {}
        }

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,(newVal) => {
            if(newVal){
                GetInfo()
                isDisabled.value = false
                setArr = []
                state.repeatDis = false
                if(props.repairInfo !== ''){
                    titleCon.value = $t('qrKpcKxIdTkDj19LmvB1v')
                    state.ruleForm = JSON.parse(props.repairInfo)
                    setTimeout(() => {
                        if(setArr.length !== 0){
                            setArr.map(i => {
                                if(JSON.parse(props.repairInfo).pid === i.id){
                                    state.ruleForm.pName = i.name
                                }
                            })
                        }
                        if(JSON.parse(props.repairInfo).pid === '0'){
                            state.ruleForm.pName = JSON.parse(props.repairInfo).name
                            isDisabled.value = true
                        }
                    },200)
                }else{
                    titleCon.value = $t('xwa8Po0XO4jEuXjRsMj')
                    state.ruleForm = {
                        id: '',
                        name: '',
                        code: '',
                        pid: '',
                        pName: '', // 用于显示
                        sort: 100,
                        remark: '',
                    }
                }
            }
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            organizaOption,
            organizaChange,
            isDisabled
        }
    },
} )
</script>
<style scoped lang="scss">
    :deep(.el-select){
        width: 100%;
    }
</style>